package com.test.thread;

import java.util.Random;

import org.apache.log4j.Logger;

public class MyThreadManager extends Thread {
	static final Logger log = Logger.getLogger(MyThreadManager.class);

	private static final int MAX = 3;

	private MyThread[] tasks = new MyThread[MAX];

	public MyThreadManager() {
		super("MyThreadManager");
		for (int i = 0; i < tasks.length; i++) {
			String id = String.valueOf(i);
			if (id.length() < 2) {
				id = "0" + id;
			}
			tasks[i] = new MyThread(id);
			tasks[i].start();
		}
	}

	public void run() {

		while (true) {
			distributeJob();
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
				log.error("InterruptedException in MyThreadManager.run()", e);
			}
		}

	}

	private boolean isStillAlive() {
		for (int i = 0; i < tasks.length; i++) {
			log.warn(tasks[i] + " is alive : " + tasks[i].isAlive());
//			if(!tasks[i].isAlive()){
//				log.warn(tasks[i] + " is NOT alive start a new Thread...");
//				tasks[i] = new MyThread((new Random().nextInt(10) + 11 + ""));
//				tasks[i].start();
//				log.warn(tasks[i] + ",new thread started.");
//			}
			
		}
		return true;
	}

	private boolean isAllJobDone() {
		for (MyThread task : tasks) {
			if (!task.isDone()) {
				log.warn(task + " is NOT done : " + task.isDone());
				return false;
			}
		}
		return true;
	}

	private void distributeJob() {

		isStillAlive();

		if (!isAllJobDone()) {
			log.info("Jobs are not finished yet.");
			return;
		}

		log.info("Distributing jobs...");

		int[] jobs = genJobs();

		for (int i = 0; i < tasks.length; i++) {
			tasks[i].setTaskId(jobs[i]);
			synchronized (tasks[i]) {
				tasks[i].notify();
			}
		}

		log.info("Distributing jobs finished.");
	}

	private static int[] genJobs() {
		Random rnd = new Random();
		int[] t = new int[MAX];
		for (int i = 0; i < t.length; i++) {
			t[i] = rnd.nextInt();
		}
		return t;
	}

	public static void main(String[] args) {

		MyThreadManager mm = new MyThreadManager();
		mm.start();

	}

}
